package io.zhengsh.nio.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class DatagramChannelClient2 {

	public static void main(String[] args) throws IOException, InterruptedException {
		DatagramChannel channel = DatagramChannel.open();
		InetSocketAddress socketAddress =
				new InetSocketAddress("127.0.0.1", 25000);
		channel.bind(socketAddress);
		channel.connect(socketAddress);
		ByteBuffer buffer = ByteBuffer.wrap("发送 DataGram 测试数据".getBytes(StandardCharsets.UTF_8));
		channel.write(buffer);
		System.out.println("write success!");

		// buffer
		ByteBuffer readBuffer = ByteBuffer.allocate(1024);
		while (true) {
			readBuffer.clear();
			channel.read(readBuffer);
			readBuffer.flip();
			System.out.println(StandardCharsets.UTF_8.decode(readBuffer));
			TimeUnit.SECONDS.sleep(2);
		}
	}
}
